<template>
  <div class="create-or-edit">
    <el-form>
      <el-form-item label="角色名称">
        <el-input v-model="role.name"></el-input>
      </el-form-item>
      <el-form-item  label="角色编码">
        <el-input v-model="role.code"></el-input>
      </el-form-item>
      <el-form-item label="角色描述">
        <el-input v-model="role.description" type="textarea"></el-input>
      </el-form-item>
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </el-form>
  </div>
</template>
<script>
import { saveOrUpdate, getRoleById } from '@/services/role'
export default {
  name: 'CreateOrEdit',
  props: {
    isEdit: {
      type: Boolean,
      // 默认为添加功能
      default: false
    },
    roleId: {
      type: [Number, String]
    }
  },
  created () {
    if (this.isEdit) {
      console.log(this.isEdit)
      //  加载上级角色信息
      this.loadRoleById()
    }
  },
  data () {
    return {
      role: {
        name: '',
        code: '',
        description: ''
      }
    }
  },
  methods: {
    async loadRoleById () {
      // console.log(this.roleId)
      const { data } = await getRoleById(this.roleId)
      // console.log(data)
      if (data.code === '000000') {
        // 将上级菜单数据保存，并绑定给视图解构
        this.role = data.data
      }
    },
    // 点击取消按钮
    onCancel () {
    // 向父组件传递取消的状态
      this.$emit('fail')
      // 关闭提示框(需要子组件向父组件传递取消的状态)并清除表单
      this.$message.error('已取消')
      this.role = {}
    },
    // 点击确定按钮
    async onSubmit () {
      const { data } = await saveOrUpdate(this.role)
      // console.log(data)
      if (data.code === '000000') {
        // 关闭提示框(需要子组件向父组件传递添加成功的状态)并清除表单
        this.$emit('success')
        // 设置成功提示
        this.$message.success('添加成功')
        // 清除表单
        this.role = {}
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
